<?php

namespace App\Remote\Guanyuan\GuanyuanV3;

use Closure;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;

class Remote extends \App\Remote\Remote
{
    static function getBaseUri(): string
    {
        // TODO: Implement getBaseUri() method.
        return "https://kuafu.guandatacloud.com";
    }

    public static function buildBasicHeaders(): array
    {
        return ["Content-Type" => "application/json"]; // TODO: Change the autogenerated stub
    }

    public static function getHandlerStack(): HandlerStack
    {
        //获取基础中间件
        $handleStack = parent::getHandlerStack();
        //增加重试中间件
        $handleStack->after(
            "logMiddleware",
            Middleware::retry(
                function (
                    int $retryTimes,
                    Request $request,
                    Response $response = null,
                    \Exception $exception = null
                ) {
                    if ($retryTimes >= 10) {
                        return false;
                    }

                    if ($exception instanceof ConnectException) {
                        return true;
                    }

                    if (!is_null($response)) {
                        $responseContents = $response->getBody()->getContents();
                        $response->getBody()->rewind();
                        $responseContentsArr = jsonToArr($responseContents, []);
                        if ($responseContentsArr) {
                            if (empty($responseContentsArr['response']) || empty($responseContentsArr['response']['data'])) {
                                return true;
                            }
                        }
                    }
                    return false;
                }, function (int $retryTimes) {
//                return 1000 * 2;
                return 1000 * 10 * $retryTimes;
            }
            ), "retryMiddleware"
        );

        return $handleStack; // TODO: Change the autogenerated stub
    }

    public static function registerResponseHandle(): Closure
    {
        return function () {
            list($responseHttpCode, $responseOriginalContents) = func_get_args();
            if ($responseHttpCode != ResponseAlias::HTTP_OK) {
                throw new \Exception($responseOriginalContents);
            }

            if (isJson($responseOriginalContents)) {
                return jsonToArr($responseOriginalContents, $responseOriginalContents);
            }

            throw new \Exception("json 解析失败 [{$responseOriginalContents}]");
        }; // TODO: Change the autogenerated stub
    }

}
